package com.example.demo01.controller;

import com.example.demo01.entity.UserEntity;
import com.example.demo01.jpa.UserJPA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * @Description:
 * @Author : hzq
 * @Date : 2020-04-28
 * @Project: demo01
 */

@Controller
//@RestController
@RequestMapping(value = "/login")
public class UserLoginController {

    @Autowired
    private UserJPA userJPA;

    @RequestMapping(value = "/loginIn", method = RequestMethod.GET)
    public String loginIn(UserEntity userEntity, HttpServletRequest request, Model model) {
        System.out.println("userEntity: " + userEntity);
        // 根据用户名查询输入用户是否存在
        Optional<UserEntity> name = userJPA.findOne(new Specification<UserEntity>() {
            @Override
            public Predicate toPredicate(Root<UserEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                criteriaQuery.where(criteriaBuilder.equal(root.get("tName"), userEntity.gettName()));
                return null;
            }
        });
        // 如果查询到该用户存在，则name.isPresent()为true 否则为false
        if(!name.isPresent()){
            request.getSession().setAttribute("msg", "user is not exist, login faild!!!");
            return "login_faild" ;
        } else if (!userEntity.gettPwd().equals(name.get().gettPwd())) {
            request.getSession().setAttribute("msg", "password is wrong!!! please resume input passwprd!");
            return "login_faild";
        }

        request.getSession().setAttribute("username", userEntity.gettName());
        return "login_success";
    }

    @RequestMapping(value = "/toLogin")
    public String toLoginView(){
        return "login";
    }
}
